<?php

namespace App\Http\Controllers\Web;

use Illuminate\Http\Request;
use DB;
use Illuminate\Support\Facades\Cookie;
use App\Repositorys\ShopRepository;

class ShopController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->middleware('CheckUserLogin')->except(['weixin_callback_url']);
    }

    public function index()
    {
        $user = Request()->get('user');
        $today_take_scrip_count = app(ShopRepository::class)->getTodayTakeScripCount($user->id);
        return view('web.shop.index', compact('user', 'today_take_scrip_count'));
    }

    public function my_scrip(Request $request)
    {
        $act = $request->act;
        $user = Request()->get('user');

        if ($act == 'put') {
            $scrips = DB::table('user_put_scrip')->where('user_id', $user->id)->orderBy('id', 'desc')->paginate(2);
            $scrip_ids = array_column($scrips->items(), 'id');
        }
        if ($act == 'take') {
            $scrip_ids = DB::table('user_take_scrip')->where('user_id', $user->id)->pluck('scrip_id')->toArray();
            $scrips = DB::table('user_put_scrip')->whereIn('id', $scrip_ids)->orderBy('id', 'desc')->paginate();
        }

        $images = DB::table('user_put_scrip_to_image')->whereIn('scrip_id', $scrip_ids)->get()->toArray();
        foreach ($images as $key => $value) {
            $array[$value->scrip_id][] = $value;
        }

        foreach ($scrips as $key => $value) {
            $scrips[$key]->created_at = date('Y-m-d H:i', strtotime($value->created_at));
            $scrips[$key]->images = isset($array[$value->id]) ? $array[$value->id] : [];
        }

        return view('web.shop.my_scrip', compact('scrips'));
    }

    public function weixin_callback_url(Request $request)
    {
        $previous = urldecode($request->previous);
        $config = Config('common.wxmp');
        $OAuth = new \Yurun\OAuthLogin\Weixin\OAuth2($config['AppID'], $config['AppSecret']);
        $session_weixin_state = session('session_weixin_state');
        $accessToken = $OAuth->getAccessToken($session_weixin_state);
        $openid = $OAuth->openid;

        $user = DB::table('user')->where('wx_openid', $openid)->first();
        if (!empty($user)) {
            DB::table('user_login_log')->where('user_id', $user->id)->update(['status' => 0]);
            $user_id = $user->id;
        } else {
            $data = ['wx_openid' => $openid];
            $user_id = DB::table('user')->insertGetId($data);
        }

        $user_token = md5($user_id . time());
        $data_user_login_log = ['user_id' => $user_id, 'token' => $user_token];
        DB::table('user_login_log')->insert($data_user_login_log);
        Cookie::queue('user_token', $user_token, Config('common.user_hold_login_time'));
        return redirect($previous);
    }
}
